package com.ruoyi.demo.controller.User;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.demo.domain.vo.inviteVo;
import com.ruoyi.demo.service.IInviteUserService;
import com.ruoyi.demo.util.ResultUtil;
import com.ruoyi.system.domain.Meet;
import com.ruoyi.system.domain.MeetLog;
import com.ruoyi.system.domain.vo.UnInviteUserVo;
import com.ruoyi.demo.domain.vo.UserInviteVO;
import com.ruoyi.system.domain.Invite;
import com.ruoyi.system.domain.MeetUser;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 33692
 */
@RestController
@RequestMapping("/demo/invite")
public class UserInviteController extends BaseController {

    @Autowired
    private IInviteService inviteService;
    @Resource
    private IInviteUserService inviteUserService;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IMeetService meetService;

    @Autowired
    private IMeetUserService meetUserService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IMeetLogService meetLogService;

    @GetMapping("/inviteList")
    public ResultUtil getInviteList() {
        System.out.println(getUserId());
        return new ResultUtil(true, inviteUserService.getInviteByInviteeId(Math.toIntExact(getUserId())));
    }
     /**
     * 获取未邀请用户列表
     */
//    @PreAuthorize("@ss.hasPermi('demo:user:list')")
    @GetMapping("/userList")
    public TableDataInfo list(UnInviteUserVo unInviteUserVo) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        unInviteUserVo.setInviterId(userId);

        startPage(); // 启动分页功能

        // 查询未邀请的用户列表，并根据传入的 SysUser 字段进行过滤
        List<SysUser> filteredUsers = userService.selectUnInviteUserList(unInviteUserVo);

        return getDataTable(filteredUsers); // 返回分页后的结果
    }
    /**
     * 获取该用户邀请列表(用户为邀请人)
     */
//    @PreAuthorize("@ss.hasPermi('demo:invite:list')")
    @GetMapping("/list")
    public TableDataInfo list(Invite invite)
    {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        invite.setInviterId(userId);

        startPage();


        List<Invite> list = inviteService.selectInviteList(invite);
        List<UserInviteVO> userInviteVOList = new ArrayList<>();
        for (Invite invite1 : list) {
            UserInviteVO userInviteVo = new UserInviteVO();
            userInviteVo.setInvite(invite1);
            userInviteVo.setMeet(meetService.selectMeetByMeetId(Math.toIntExact(invite1.getMeetId())));
            userInviteVo.setUser(sysUserService.selectUserById(invite1.getInviteeId()));
            userInviteVOList.add(userInviteVo);
        }
        System.out.println(getDataTable(userInviteVOList).toString());
// 返回原始分页数据，保留总记录数
        TableDataInfo dataTable = getDataTable(list); // 基于分页插件的原始查询
        dataTable.setRows(userInviteVOList); // 替换返回的行数据为组装后的 VO 列表

        return dataTable;
//        return getDataTable(userInviteVoList);
    }

    /**
     * 获取该用户被邀请列表(用户为被邀请人)
     */
//    @PreAuthorize("@ss.hasPermi('demo:invite:list')")
    @GetMapping("/beList")
    public TableDataInfo beList(Invite invite)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        invite.setInviteeId(userId);
        startPage();
        List<Invite> list = inviteService.selectInviteList(invite);
        List<UserInviteVO> userInviteVOList = new ArrayList<>();
        for (Invite invite1 : list) {
            UserInviteVO userInviteVo = new UserInviteVO();
            userInviteVo.setInvite(invite1);
            userInviteVo.setMeet(meetService.selectMeetByMeetId(Math.toIntExact(invite1.getMeetId())));
            userInviteVo.setUser(sysUserService.selectUserById(invite1.getInviterId()));
            userInviteVOList.add(userInviteVo);
        }
        return getDataTable(userInviteVOList);
    }

    /**
     * 删除邀请信息
     */
//    @PreAuthorize("@ss.hasPermi('demo:invite:remove')")
    @Log(title = "邀请信息管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(inviteService.deleteInviteByIds(ids));
    }

    /**
     * 接受邀请
     */
//    @PreAuthorize("@ss.hasPermi('demo:invite:edit')")
    @Log(title = "邀请信息管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Invite invite)
    {
        System.out.println(invite.toString());
        invite.setStatus("1");
        if(inviteService.updateInvite(invite) == 1){
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userId = loginUser.getUserId();
            MeetUser meetUser = new MeetUser();
            meetUser.setMeetId(invite.getMeetId());
            meetUser.setUserId(userId);
            //插入meetlog
            int inserM = meetUserService.insertMeetUser(meetUser);
            if(inserM == 1){
                MeetLog meetLog = new MeetLog();
                Meet meet = meetService.selectMeetByMeetId(Math.toIntExact(invite.getMeetId()));
                meetLog.setMeetId(invite.getMeetId());
                meetLog.setStatus(meet.getStatus());
                meetLog.setTheme(meet.getTheme());
                meetLog.setMeetContent(meet.getMeetContent());
                meetLog.setStartTime(meet.getStartTime());
                meetLog.setEndTime(meet.getEndTime());
                meetLog.setCreatedAt(meet.getCreatedAt());
                meetLog.setUpdateAt(meet.getUpdateAt());

                SysUser sysUser = userService.selectUserById(userId);
                meetLog.setUserId(userId);
                meetLog.setAttendUser(sysUser.getUserName());
                meetLog.setIsDeleted("0");
                meetLogService.insertMeetLog(meetLog);

            }
            return toAjax(inserM);
        }
        // 如果邀请更新失败，则返回失败信息
        return AjaxResult.error("邀请更新失败");
    }

    /**
     * 用户邀请其他用户参会
     */
//    @PreAuthorize("@ss.hasPermi('demo:invite:add')")
    @Log(title = "邀请信息管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody List<Invite> invites)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();

        // 为每个邀请对象设置邀请者 ID
        invites.forEach(invite -> invite.setInviterId(userId));
        // 调用批量插入的服务方法
        int rows = inviteService.insertBatch(invites);

        return toAjax(rows);
    }
    @GetMapping("/getInviteByInviterIdAndMeetId/{inviterId}/{meetId}")
    public ResultUtil getInviteByInviterIdAndMeetId(@PathVariable int inviterId,@PathVariable int meetId) {
        System.out.println("inviterId:"+inviterId+"meetId:"+meetId);
        return new ResultUtil(true,inviteUserService.getInviteByInviterIdAndMeetId(inviterId,meetId,getUserId()));
    }
    @PutMapping("/updateInviteStatus/{meetId}")
    public ResultUtil updateInviteStatus(@PathVariable int meetId) {
        return new ResultUtil(inviteUserService.updateInviteStatus(Math.toIntExact(getUserId()),meetId));
    }
    @GetMapping("/getInviteBySearch")
    public ResultUtil getInviteBySearch(@RequestParam("item") String item) {
        return new ResultUtil(true,inviteUserService.getInviteBySearch(item,getUserId()));
    }

}
